package com.xiaolin.security.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import com.xiaolin.security.model.Member;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/10/8
 * @Version 1.0
 */
@Controller
public class LoginController {

    /**
     * 登录接口
     * @param model
     */
    @RequestMapping("/login")
    public String login(Model model){
        String principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        if(principal.equals("anonymousUser")){
            System.out.println("我要登录");
            return "login";
        }else {
            System.out.println("用户已登录");
            UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            System.out.println(userDetails.getUsername());
            model.addAttribute("username",userDetails.getUsername());
            return "index";
        }
    }

    /**
     * 登录成功请求的接口
     * @param model
     */
    @RequestMapping("/index")
    public String index(Model model){
        System.out.println("登录成功");
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        for (GrantedAuthority authority : authorities) {
            System.out.println(authority.getAuthority());
        }
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(userDetails.getUsername());
        model.addAttribute("username",userDetails.getUsername());
        return "index";
    }

    @RequestMapping("/logout2")
    public String logout(){
        System.out.println("我要注销");
        return "logout";
    }

}
